package cn.imvc.app.models;

import java.util.Iterator;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.Seller;
import cn.imvc.app.entities.Storage;
import cn.imvc.app.entities.StorageType;
import cn.imvc.app.repositories.StorageRepository;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;

@Service
public class StorageModelImpl implements StorageModel {

	@Autowired
	private StorageRepository storageRepository;
	@Autowired
	private SellerModel sellerModel;
	@Autowired
	private StorageTypeModel storageTypeModel;
	@Autowired
	RefRelationModel refRelationModel;
	
	public Page<Storage> find(ViewRequest viewRequest) {
		
		return storageRepository.findAll(ModelUtil.OrderByIdDesc(viewRequest));
	}

	public Storage get(int id) {
		
		return storageRepository.getOne(id);
	}

	public int save(int sellerId, int storageTypeId, Storage storage) {
	
		Seller seller = storage.getSeller();
		String code = storage.getCode();
		String name = storage.getName();
		List<Storage> sc = storageRepository.getBySellerAndCode(seller,code);
		List<Storage> sn = storageRepository.getBySellerAndName(seller, name);
		if(sc.size()>0){
			return 0;
		}else if(sn.size()>0){
			return -1;
		}
		storageRepository.saveAndFlush(storage);
		return 1;
	}
	
	public int update(int id,int sellerId, int storageTypeId, Storage storage) {
		
		Storage loadStorage = storageRepository.findOne(id);
		Seller seller = storage.getSeller();
		String code = storage.getCode();
		String name = storage.getName();
		List<Storage> sc = storageRepository.getBySellerAndCode(seller,code);
		List<Storage> sn = storageRepository.getBySellerAndName(seller, name);
		if(sc.size()>0&&!code.equals(loadStorage.getCode())){
			return 0;
		}else if(sn.size()>0&&!name.equals(loadStorage.getName())){
			return -1;
		}
		BeanUtils.copyProperties(storage, loadStorage, new String[]{"id"});
		storageRepository.saveAndFlush(loadStorage);
		return 1;
	}

	public String delete(int id) {
		String result = refRelationModel.deleteDateCheck("Storage", "id", id);
		if(result.equals("")){
			storageRepository.delete(id);
			return "";
		}else{
			return result;
		}
	}

	public void deleteBatch(int[] ids) {
		
		for (int id : ids) {
			storageRepository.delete(id);
		}
	}



}
